package com.miaomiaojia.android;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.miaomiaojia.bll.CommonData;
import com.miaomiaojia.bll.CommonTool;
import com.miaomiaojia.entity.Category;
import com.miaomiaojia.entity.StaticData;
import com.miaomiaojia.waterfall.WaterFallOption;
import com.miaomiaojia.waterfall.WaterFallView;
import com.miaomiaojia.waterfall.WaterFallView.OnScrollListener;
import com.miaomiaojia.waterfallitem.FlowView;
import com.miaomiaojia.waterfallitem.FlowViewHandler;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout.LayoutParams;

public class ListActivity extends Activity implements OnScrollListener {

	private Button categoryButton;

	private WaterFallView waterfall_scroll;
	private LinearLayout waterfall_container;
	private Display display;
	private AssetManager asset_manager;
	private List<String> image_filenames;
	private final String image_path = "images";
	private Handler handler;
	private int item_width = 95;
	private int column_count = 3;
	private int classId = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);

		display = getWindowManager().getDefaultDisplay();
		// item_width = display.getWidth() / column_count;
		column_count = display.getWidth() / item_width;
		asset_manager = getAssets();
		waterfall_scroll = (WaterFallView) findViewById(R.id.waterfall_scroll);
		waterfall_container = (LinearLayout) findViewById(R.id.waterfall_container);
		waterfall_scroll.setOnScrollListener(this);
		
		initLayout();

		categoryButton = (Button) findViewById(R.id.category);
		categoryButton.setText("全部");
		categoryButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showCategoryChoose();
			}
		});
		CommonData.loadCategoryData();
	}

	public void showCategoryChoose() {
		List<String> list = new ArrayList<String>();
		for (Category category : StaticData.CategoryList) {
			list.add(category.getTitle());
		}
		new AlertDialog.Builder(ListActivity.this)
				.setTitle("选择分类")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setSingleChoiceItems(
						list.toArray(new CharSequence[list.size()]), -1,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// 用户单击的是【确定】按钮
								if (which == DialogInterface.BUTTON_POSITIVE) {
								}
								// 用户单击的是【取消】按钮
								else if (which == DialogInterface.BUTTON_NEGATIVE) {
									dialog.dismiss();
								}
								// 选项中
								else {
									Category category = StaticData.CategoryList
											.get(which);
									String jsonString = "{id:"
											+ category.getId() + ",title:'"
											+ category.getTitle() + "'}";
									categoryButton.setText(category.getTitle());
									classId = category.getId();
									waterfall_scroll.current_page = 0;
									waterfall_container.removeAllViews();
//									AddItemToContainer(waterfall_scroll.current_page,
//											waterfall_scroll.pageCount);
									initLayout();
									dialog.dismiss();
								}
							}
						}).setNegativeButton("取消", null).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_list, menu);
		return true;
	}

	private void initLayout() {
		WaterFallOption fallOption = new WaterFallOption(waterfall_container,
				item_width, column_count, display.getWidth());
		waterfall_scroll.commitWaterFall(fallOption, waterfall_scroll);
		handler = new FlowViewHandler(waterfall_scroll);
		AddItemToContainer(waterfall_scroll.current_page,
				waterfall_scroll.pageCount);
	}

	private void AddItemToContainer(final int pageindex, final int pagecount) {
		new Thread() {
			@Override
			public void run() {
				String url = getResources().getString(R.string.host)
						+ getResources().getString(R.string.list);
				url = String.format(url, pageindex + 1, classId, 1, 90);
				String result = CommonTool.getResult(url);
				JSONObject data;
				try {
					data = new JSONObject(result);
					int status = data.getInt("status");
					if (status == 1) {
						JSONArray array = new JSONArray(data.getString("data"));
						for (int i = 0; i < array.length(); i++) {
							JSONObject produce = array.getJSONObject(i);
							String imgurl = produce.getString("small_img_url");
							AddImage(imgurl,
									(int) Math
											.ceil(waterfall_scroll.loaded_count
													/ (double) column_count),
									produce.getInt("id"));
						}
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void AddImage(String filename, int rowIndex, int id) {
		FlowView item = new FlowView(this);
		// item.setPadding(3, 1, 5, 4);
		item.setRowIndex(rowIndex);
		item.setId(id);
		item.setViewHandler(handler);
		item.setFileName(filename);
		item.setItemWidth(item_width);
		item.LoadImage();

		Intent it = new Intent(ListActivity.this, DetailActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("id", id);
		it.putExtras(bundle);
		item.setClickIntent(it);

		LayoutParams lp = new LayoutParams();
		lp.setMargins(0, 0, 0, 5);
		item.setLayoutParams(lp);
	}

	@Override
	public void onBottom() {
		AddItemToContainer(++(waterfall_scroll.current_page),
				waterfall_scroll.pageCount);
	}

	@Override
	public void onTop() {
	}

	@Override
	public void onScroll() {
		
	}

	@Override
	public void onAutoScroll(int l, int t, int oldl, int oldt) {
	}
}
